const express = require('express')
const app = express()
const getDataRouter = require('./getData/index.js')
const { errorHandler } = require('./middleware/errorHandler')
const {
  globalLimiter,
  apiLimiter,
  adminLimiter,
} = require('./middleware/rateLimiter')
const {
  loggingMiddleware,
} = require('./middleware/loggingMiddleware')
const { testConnection } = require('./db')
const PORT = 7204
const cors = require('cors')

// 基础中间件
app.use(cors())
app.use(express.json({ limit: '10mb' })) // 限制请求体大小

// 全局限流中间件
app.use(globalLimiter)
// 请求日志中间件
app.use(loggingMiddleware)

// 数据库状态端点
app.get('/db-status', adminLimiter, async (req, res) => {
  try {
    const { getPoolStatus } = require('./db')
    const poolStatus = await getPoolStatus()

    res.status(200).json({
      timestamp: new Date().toISOString(),
      database: {
        pool: poolStatus,
      },
    })
  } catch (error) {
    console.error('获取数据库状态失败:', error)
    res.status(500).json({
      status: 'error',
      timestamp: new Date().toISOString(),
      error: '获取数据库状态失败',
      message: error.message,
    })
  }
})

// 健康检查端点
app.get('/health', async (req, res) => {
  try {
    // 检查数据库连接
    const dbStatus = await testConnection()

    // 获取数据库连接池状态
    const { getPoolStatus } = require('./db')
    const poolStatus = await getPoolStatus()

    // 获取系统资源使用情况
    const os = require('os')
    const totalMem = os.totalmem()
    const freeMem = os.freemem()
    const usedMem = totalMem - freeMem
    const memUsage = process.memoryUsage()

    // 获取进程信息
    const processInfo = {
      pid: process.pid,
      uptime: process.uptime(),
      nodeVersion: process.version,
      platform: process.platform,
      memoryUsage: {
        rss: `${Math.round(memUsage.rss / 1024 / 1024)} MB`,
        heapTotal: `${Math.round(memUsage.heapTotal / 1024 / 1024)} MB`,
        heapUsed: `${Math.round(memUsage.heapUsed / 1024 / 1024)} MB`,
        external: `${Math.round(memUsage.external / 1024 / 1024)} MB`,
        arrayBuffers: `${Math.round((memUsage.arrayBuffers || 0) / 1024 / 1024)} MB`,
      },
    }

    // 返回健康状态
    res.status(dbStatus ? 200 : 503).json({
      status: dbStatus ? 'ok' : 'error',
      timestamp: new Date().toISOString(),
      server: {
        hostname: os.hostname(),
        platform: os.platform(),
        arch: os.arch(),
        cpus: os.cpus().length,
        loadAvg: os.loadavg(),
        memory: {
          total: `${Math.round(totalMem / 1024 / 1024)} MB`,
          free: `${Math.round(freeMem / 1024 / 1024)} MB`,
          used: `${Math.round(usedMem / 1024 / 1024)} MB`,
          usagePercent: `${Math.round((usedMem / totalMem) * 100)}%`,
        },
      },
      process: processInfo,
      database: {
        status: dbStatus ? 'connected' : 'disconnected',
        pool: poolStatus,
      },
    })
  } catch (error) {
    console.error('健康检查失败:', error)
    res.status(500).json({
      status: 'error',
      timestamp: new Date().toISOString(),
      error: '健康检查执行失败',
      message: error.message,
    })
  }
})

// API路由（应用API限流）
app.use('/api', apiLimiter, getDataRouter)
// 404处理
app.all(/(.*)/, (req, res) => {
  res.setHeader('Content-Type', 'text/plain; charset=utf-8')
  res.status(404).send('哇！抓到一只迷路的小猫咪')
})

// 全局错误处理中间件
app.use(errorHandler)

// 未捕获的异常处理
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常:', err)
  // 记录错误并优雅退出
  process.exit(1)
})

// 未处理的Promise拒绝处理
process.on('unhandledRejection', (err) => {
  console.error('未处理的Promise拒绝:', err)
  // 记录错误但不退出进程
})

// 启动服务器
const server = app.listen(PORT, () => {
  console.log(`服务器已启动: http://localhost:${PORT}`)
  console.log(`健康检查: http://localhost:${PORT}/health`)
})

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('收到SIGTERM信号，正在优雅关闭...')
  server.close(() => {
    console.log('服务器已关闭')
    process.exit(0)
  })
})
